package net.yxsoft.service.formdisigner;

import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.enumclass.WhetherEnumCls;
import net.yxsoft.kit.CustomDb;
import net.yxsoft.kit.ToolDateTime;
import net.yxsoft.model.formdesigner.Form;
import net.yxsoft.model.formdesigner.FormField;
import net.yxsoft.model.infrastructure.TsDatamodelProperties;
import net.yxsoft.resource.SqlRes;
import net.yxsoft.resource.TableRes;
import rapid.core.SqlList;
import rapid.core.TResult;
import rapid.jfinal.BaseService;
import rapid.jfinal.Pagination;
import rapid.jfinal.ParamKeyMap;
import rapid.util.StrKit;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author zhaohaibo
 */
public class FormService extends BaseService {

  public Form findById(ParamKeyMap params) {
    return Form.dao.findFirst(Db.getSqlPara(SqlRes.FORM_DESIGNER + "findFormById", params.toKv()));
  }

  public List<Form> find(ParamKeyMap params) {
    return Form.dao.find(Db.getSqlPara(SqlRes.FORM_DESIGNER + "findForm", params.toKv()));
  }


  public Record getImportModelTable(String fromid) {
    Record record=Db.findFirst("select t1.conflict_id from fn_form t left join ts_party t1 on t.model=t1.name where t.id=?",fromid);
    if(record==null || StrKit.isBlank(record.getStr("conflict_id")) ){
      record=Db.findFirst("select conflict_id from  ts_party  where name='FN_FORM_DATA'");
    }
    return record;
  }

  public Pagination find(ParamKeyMap params, Pagination pg) {

    return query(SqlRes.FORM_DESIGNER + "findForm", params.toKv(), pg);
  }

  /**
   * 检查编号和名称是否重复
   *
   * @return
   */
  public TResult checkDulpicate(ParamKeyMap params) {
    return checkDulpicate(params.get("id"), params.get("name"), params.get("code"));
  }

  /**
   * 检查编号和名称是否重复
   *
   * @return
   */
  public TResult checkDulpicate(String id, String name, String code) {
    Kv kv = Kv.create();
    setDuplicateKv(kv, id, name, code);

    Form temp = Form.dao.findFirst(Db.getSqlPara(SqlRes.FORM_DESIGNER + "checkFormDuplicate", kv));

    if(temp != null) {
      if(temp.getName().equals(name)) {
        return fail().msg("已存在相同的名称。");
      }

      if(temp.getCode().equals(code)) {
        return fail().msg("已存在相同的编号。");
      }
    }

    return success();
  }

  public TResult add(Form obj) {
    if(obj == null) {
      return fail();
    }

    if(!StrKit.isBlank(obj.getIsSource()) && WhetherEnumCls.YES.getValue().equals(obj.getIsSource())){

      if(StrKit.isBlank(obj.getSourceName())){

        return fail().msg("请输入第三方数据源视图名称");
      }
    }

    TResult rs = checkDulpicate(null, obj.getName(), obj.getCode());

    if(rs.isFail()) {
      return rs;
    }
    TResult ts= obj.save() ? success() : fail();

    if(ts.isSuccess() && StrKit.notBlank(obj.getModel())){
      List<TsDatamodelProperties> tsDatamodelPropertiesList=TsDatamodelProperties.dao.find("select t.* from ts_datamodel_properties t left join ts_party t1 on t.model_id=t1.conflict_id where t1.name=? and t.state=1 order by id",obj.getModel());
      for(TsDatamodelProperties tsDatamodelProperties:tsDatamodelPropertiesList){
        FormField formField=new FormField();
        formField.setFormId(obj.getId());
        formField.setTitle(tsDatamodelProperties.getAttribDescn());
        formField.setName(tsDatamodelProperties.getAttribName().toUpperCase()+"|"+tsDatamodelProperties.getAttribType().toUpperCase());
        formField.setType(StrKit.notBlank(tsDatamodelProperties.getCodeType())?"picker":"textbox");
        formField.setState(1);
        formField.setCreated(ToolDateTime.getDate());
        formField.setSort(new BigDecimal(100));
        if(StrKit.notBlank(tsDatamodelProperties.getCodeType())){
          formField.setCodeResource(tsDatamodelProperties.getCodeName()+"|"+tsDatamodelProperties.getCodeCustomId()+"|"+tsDatamodelProperties.getCodeType());
          formField.setCodeLeaf(tsDatamodelProperties.getCodeLeaf());
          formField.setCodeName(tsDatamodelProperties.getCodeName());
          formField.setCodeType(tsDatamodelProperties.getCodeType());
        }
        formField.setField(tsDatamodelProperties.getAttribName().toUpperCase());
        formField.setGridFieldVisible(0);
        formField.setIsSearch("0");
        formField.setColSpan(0);
        formField.setDataOnly("0");
        formField.setIsSum("0");
        formField.setIsTypeSum("0");
        formField.setIsExport("1");
        formField.setIsAutocode("0");
        formField.setIsEditor("1");
        formField.save();
      }

    }
    return ts;
  }

  public TResult update(Form obj) {
    if(obj == null) {
      return fail();
    }

    if(!StrKit.isBlank(obj.getIsSource()) && WhetherEnumCls.YES.getValue().equals(obj.getIsSource())){

      if(StrKit.isBlank(obj.getSourceName())){

        return fail().msg("请输入第三方数据源视图名称");
      }
    }

    TResult rs = checkDulpicate(obj.getId(), obj.getName(), obj.getCode());

    if(rs.isFail()) {
      return rs;
    }

    Form old = Form.dao.findById(obj.getId());
    if(old == null) {
      return fail().msg("记录不存在或已被删除。");
    }

    old.setParentid(obj.getParentid());
    old.setName(obj.getName());
    old.setCode(obj.getCode());
    old.setIcon(obj.getIcon());
    old.setType(obj.getType());
    old.setNote(obj.getNote());
    old.setSort(obj.getSort());
    old.setModel(obj.getModel());
    old.setColSize(obj.getColSize());
    old.setAttrib01(obj.getAttrib01());
    old.setBlockChainMode(obj.getBlockChainMode());
    old.setIsSource(obj.getIsSource());
    old.setSourceName(obj.getSourceName());

    return old.update() ? success() : fail();
  }

  public TResult toggleDisabled(String id, String state) {
    if(StrKit.isEmpty(id)) {
      return success();
    }

    CustomDb.updateWithExceptionHandling("update " + TableRes.FORM + " set state = ? where id = ?", state, id);

    return success();
  }

  public TResult remove(String id) {
    if(StrKit.isEmpty(id)) {
      return success();
    }

    SqlList sqls = new SqlList();

    sqls.add("delete from %s where id = %s", TableRes.FORM, id)
            .add("delete from %s where form_id = %s", TableRes.FORM_FIELD, id);

    Db.batch(sqls, 10000);

    return success();
  }

  private void setDuplicateKv(Kv kv, String id, String name, String code) {
    if(StrKit.hasValue(name)) {
      kv.set("name", name);
    }

    if(StrKit.hasValue(code)) {
      kv.set("code", code);
    }

    if(id != null) {
      kv.set("id", id);
    }
  }

  /**
   * 根据编号获取表单主表
   * */
  public Form getFnFormByCode(String code){
    return Form.dao.findFirst("select group_concat(concat(b.id,'|',b.name,'|',b.code) order by b.sort) soninfo,a.* \n" +
            "  from fn_form a\n" +
            "   left join fn_form b on a.id = b.parentid\n" +
            "  where a.code = ? \n" +
            "  order by a.type asc, a.state desc, a.sort desc, a.created desc", code);
  }



  /**
   * 获取动态表单上链方式
   * @return
   */
  public List<Record> getBlockChainMode() {

    return Db.find("select codename ,customid from ts_code where parentcustomid=? and enabled='1'", PropKit.get("blockchainmode"));
  }


  /**
   * 获取模型
   * @return
   */
  public List<Record> getModel() {

    return Db.find("select  name,cnname from ts_party where (name like '%s_%' or name like '%v_%') and name !='s_log' and name !='s_synonyms' and name !='s_syn_details' and name !='s_syn_details' and name not like '%s_lifecyc%'  and name not like '%s_blo%'");
  }

}
